package userServiceDemo.service.impl;


import cn.t11.dm.pojo.Dto;
import cn.t11.dm.util.DtoUtil;
import cn.t11.dm.util.RedisUtil;
import cn.t11.dm.util.TokenUtil;
import userServiceDemo.entity.DmImage;
import userServiceDemo.entity.DmUser;
import userServiceDemo.entity.LoginVo;
import userServiceDemo.entity.TokenVo;
import mapper.DmImageMapper;
import mapper.DmUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import userServiceDemo.service.DmUserService;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-01-14
 */
@Service
public class DmUserServiceImpl implements DmUserService {

    @Autowired
    DmUserMapper dmUserMapper;

    @Autowired
    DmImageMapper dmImageMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    TokenUtil tokenUtil;

    public Dto doLogin(String phone, String password,HttpServletRequest request) {
        DmUser dmUser = dmUserMapper.doLogin(phone, password);
        if (dmUser!=null) {
            if (dmUser.getPassword().equals(password)) {
                DmImage dmImage = dmImageMapper.selectImageBy(dmUser.getId());
                LoginVo loginVo=new LoginVo();
                BeanUtils.copyProperties(dmImage,loginVo);
                BeanUtils.copyProperties(dmUser,loginVo);
                // 生成token
                String agent = request.getHeader("User-Agent");
                String token = tokenUtil.generateToken(agent, phone);
                //保存到redis
                redisUtil.set(token,loginVo,600);//600秒失效
                TokenVo tokenVo=new TokenVo();
                tokenVo.setToken(token);
                tokenVo.setExpTime(600);
                tokenVo.setGenTime(new Date().getTime());
                List list=new ArrayList();
                list.add(loginVo);
                list.add(tokenVo);
                return DtoUtil.returnSuccess("发送成功",list);
            }else {
                return DtoUtil.returnFail("账号或密码错误",1006);
            }
        }else {
            return DtoUtil.returnFail("用户不存在",1000);
        }
    }
}
